package inabit.expressioncompiler.productions;

import inabit.compiler.parser.grammar.NonTerminal;
import inabit.compiler.parser.grammar.Production;
import inabit.compiler.parser.grammar.Symbol;
import inabit.compiler.parser.grammar.Terminal;
import inabit.data.expression.arithmetic.ArithmeticExpression;
import inabit.data.expression.arithmetic.SubExpression;
import inabit.data.expression.arithmetic.SumExpression;
import inabit.expressioncompiler.lexical.ExpressionTokenClass;
import inabit.expressioncompiler.parser.ExpressionSemanticAction;


/**X' -> +XX'*/
/**@author Rafael Rocha*/
public class X1_Rule extends Production{
	private NonTerminal X;
	private NonTerminal X1;
	
	public X1_Rule() {
		super("X'");
	}
	
	public Symbol[] production(final NonTerminal nonTerminal) {
		X = new NonTerminal("X");
		X1 = new NonTerminal("X'");
		Symbol[] symbols = {
			new Terminal(ExpressionTokenClass.PLUS),
			X,
			X1,
			new ExpressionSemanticAction(nonTerminal) {
				public void execute() throws Exception {
					nonTerminal.code = "+:";
					if(X1.code.isEmpty()) {
						nonTerminal.code += X.code;
					}else {
						ArithmeticExpression aExpr;
						String[] right = X1.code.split(":");
						String op = right[0];
						if(op.equals("+")) {
							aExpr = new SumExpression(
								getArithmeticExpression(X.code),
								getArithmeticExpression(right[1]));
						}else if(op.equals("-")){
							aExpr = new SubExpression(
								getArithmeticExpression(X.code),
								getArithmeticExpression(right[1]));
						}else {
							throw new Exception("Cant recognize operator " + op + " in this context ");
						}
						nonTerminal.code += addArithmeticExpressionAndGetCode(aExpr);
					}
				}
			}
		};
		return symbols;
	}
}
